package com.jxstjh.conch.handler.pending;

import cn.hutool.core.collection.CollUtil;
import com.jxstjh.conch.common.domain.TaskInfo;
import com.jxstjh.conch.handler.deduplication.DeduplicationRuleService;
import com.jxstjh.conch.handler.discard.DiscardMessageService;
import com.jxstjh.conch.handler.handler.MessageHandlerHolder;
import com.jxstjh.conch.handler.shield.ShieldService;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * 消息发送执行器
 * 1、丢弃消息  详见DiscardMessageService
 * 2、消息去重  详见DeduplicationRuleService
 * 3、消息发送
 */
@Data
@Accessors(chain = true)
@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Task implements Runnable {

    @Autowired
    private MessageHandlerHolder messageHandlerHolder;
    @Autowired
    private DeduplicationRuleService deduplicationRuleService;
    @Autowired
    private DiscardMessageService discardMessageService;
    @Autowired
    private ShieldService shieldService;

    private TaskInfo taskInfo;

    @Override
    public void run() {

        // 0、丢弃消息
        if (discardMessageService.isDiscard(taskInfo)) {
            return;
        }

        // 1、屏蔽消息
        // TODO 此处实现逻辑待议
        shieldService.shield(taskInfo);

        // 2、消息去重
        deduplicationRuleService.duplication(taskInfo);

        // 3、消息发送
        if (CollUtil.isNotEmpty(taskInfo.getReceiver())) {
            messageHandlerHolder.route(taskInfo.getSendChannel()).doHandler(taskInfo);
        }
    }
}